package org.code.mallspringboot.controller;

import org.code.mallspringboot.dto.SmsProductRelationListDto;
import org.code.mallspringboot.dto.SmsSelectProductsDto;
import org.code.mallspringboot.pojo.SmsFlashPromotionProductRelation;
import org.code.mallspringboot.service.SmsFlashPromotionProductRelationService;
import org.code.mallspringboot.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/flashProductRelation")
public class SmsFlashPromotionProductRelationController {


    @Autowired
    private SmsFlashPromotionProductRelationService smsFlashPromotionProductRelationService;

    //商品列表-数据列表
    @GetMapping("/list")
    public CommonResult list(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
                             Integer flashPromotionId,Integer flashPromotionSessionId){
        List<SmsProductRelationListDto> list = smsFlashPromotionProductRelationService.selectPage
                (pageNum, pageSize, flashPromotionId, flashPromotionSessionId);
        int total = smsFlashPromotionProductRelationService.total(flashPromotionId, flashPromotionSessionId);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("list" , list);
        map.put("total" , total);
        if (!map.isEmpty()){
            return CommonResult.success(map);
        }
        return CommonResult.failed("查询失败");
    }

    //商品列表-编辑
    @PostMapping("/update/{id}")
    public CommonResult update(@PathVariable int id,@RequestBody SmsProductRelationListDto smsProductRelationListDto){
        smsProductRelationListDto.setId(id);
        if (smsFlashPromotionProductRelationService.update(smsProductRelationListDto) > 0){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败!");
    }

    //商品列表-添加
    @PostMapping("/create")
    public CommonResult create(@RequestBody SmsSelectProductsDto[] smsSelectProductsDto){
        boolean flag = false;
        for (SmsSelectProductsDto selectProductsDto : smsSelectProductsDto) {
            if (smsFlashPromotionProductRelationService.add(selectProductsDto) > 0){
                flag = true;
            }
        }
        if (flag){return CommonResult.success("添加成功");}
        return CommonResult.failed("添加失败");
    }

    //商品列表-删除
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable int id){
        if (smsFlashPromotionProductRelationService.delete(id) > 0){
            return CommonResult.success("删除成功");
        }
        return CommonResult.failed("删除失败!");
    }
}
